package cs4295asg2.stockfinder;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

//Android Service life cycle
//onCreate(),onStart(),onDestroy()
//第一次启动Service时，先后调用了onCreate(),onStart()这两个方法.
//当停止Service时，则执行onDestroy()方法，
//这里需要注意的是，如果Service已经启动了，当我们再次启动Service时，
//不会在执行onCreate()方法，而是直接执行onStart()方法

//繼承android.app.Service
public class NotifictionService extends Service {
	private Handler handler = new Handler();
	// internal db ----------------------------
	List<StockTarget> stockList;
	private BufferedReader reader = null;

	// end internal db ----------------------------
	double tagetPrice = (double) 0.5;
	double currrentPrice = 1;

	@Override
	public void onStart(Intent intent, int startId) {
		Log.e("MyService", "onStart NotificationService~~~");
		// Load data by using SharedPreferences -------------------------------
		stockList = new ArrayList<StockTarget>();
		SharedPreferences settings = getSharedPreferences("task_Pref",
				Context.MODE_PRIVATE);
		int count = settings.getInt("tCount", 0);
		String d;
		for (int j = 0; j < count; j++) {
			d = settings.getString("Task_" + j, "ERROR");
			String[] sArray = d.split(",");
			String stNo = sArray[0];
			double currP = Double.parseDouble(sArray[1]);
			double targetP = Double.parseDouble(sArray[2]);
			StockTarget stTemp = new StockTarget(stNo, currP);
			stTemp.setTargetPrice(targetP);
			stockList.add(stTemp);
		}
		// Load data by using SharedPreferences
		// --------------------------------------

		handler.postDelayed(showTime, 2000);
		super.onStart(intent, startId);

	}

	@Override
	public void onDestroy() {
		Log.e("MyService", "onDestroy NotificationService~~~");
		handler.removeCallbacks(showTime);
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.e("MyService", "onBind~~~");
		return null;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.e("MyService", "start unUnbind~~~");
		return super.onUnbind(intent);
	}



	private Runnable showTime = new Runnable() {
		@SuppressWarnings("deprecation")
		public void run() {
			// log目前時間
			Log.i("time:", new Date().toString());

			int listSize = stockList.size();
			for (int i = 0; i < listSize; i++) {
				final String stockSymbol = stockList.get(i).getNumber();
				double targetPrice = stockList.get(i).getTargetPrice();
				String validatedStockSymbol = StockDetails.validate(stockSymbol);
				String strURL = "http://download.finance.yahoo.com/d/quotes.csv?s="+ validatedStockSymbol +"&f=nsl1opc1";
				//make connection --------------------
				class HostConnection extends AsyncTask<String, Void, InputStream> {
					private Exception ex;

					@Override
					protected void onPreExecute() {
						super.onPreExecute();
					}

					protected InputStream doInBackground(String... urls) {
						try {
							// defaultHttpClient
							DefaultHttpClient httpClient = new DefaultHttpClient();
							HttpGet httpGet = new HttpGet(urls[0]);
							HttpContext localContext = new BasicHttpContext();
							HttpResponse httpResponse = httpClient.execute(httpGet, localContext);
							HttpEntity httpEntity = httpResponse.getEntity();
							return httpEntity.getContent();
						} catch (Exception e) {
							this.ex = e;
							Log.i("HostConnection", "Error in DefaultHttpClient");
							return null;
						}
					}

					@Override
					protected void onPostExecute(InputStream is) {
						super.onPostExecute(is);
						reader = new BufferedReader(new InputStreamReader(is));
						try {
							String line;
							while ((line = reader.readLine()) != null) {
								String[] RowData = line.split(",");
								String currPrice = RowData[2];
								currrentPrice = Double.parseDouble(currPrice);
								Log.i("servive's AsyncTask", stockSymbol + "'s currPrice " + currPrice);
								Toast.makeText(getApplicationContext(), stockSymbol	
										+ "'s currPrice " + currPrice, Toast.LENGTH_SHORT).show();
							}
						} catch (IOException ex) {
							ex.printStackTrace();
						} finally {
							try {
								is.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
				//make connection --------------------
				AsyncTask<String, Void, InputStream> task = new HostConnection().execute(strURL);
				try {
					task.get();
				
					// compare
					Log.i("notification", "currrentPrice" + currrentPrice + "targetPrice"+ targetPrice);
					if (currrentPrice > targetPrice) {
						// get stockList.get(i).
	
						// notification -------------------------
						// 取得Notification服務
						NotificationManager notificationManager 
							= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
						// 設定當按下這個通知之後要執行的activity
						Intent notifyIntent 
							= new Intent(NotifictionService.this, MainActivity.class);
						notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						PendingIntent appIntent = PendingIntent.getActivity(
								NotifictionService.this, 0, notifyIntent, 0);
						Notification notification = new Notification();
						// 設定出現在狀態列的圖示
						notification.icon = R.drawable.icon;
						// 顯示在狀態列的文字
						notification.tickerText = stockSymbol + " reach the target Price(" + targetPrice + ")!!";
						// 會有通知預設的鈴聲、振動、light
						notification.defaults = Notification.DEFAULT_ALL;
						// 設定通知的標題、內容
						notification.setLatestEventInfo(NotifictionService.this,
								stockSymbol + " reach the target Price(" + targetPrice + ")!!", 
										"the current price is " + currrentPrice, appIntent);
						// 送出Notification
						int notificaitionId = i;
						notificationManager.notify(notificaitionId, notification);
						// end notification -------------------------
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ExecutionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			// save data for internal storage
			SharedPreferences settings = getSharedPreferences("task_Pref", Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = settings.edit();
			int c = stockList.size();
			editor.putInt("tCount", c);
			for (int i = 0; i < c; i++) {
				editor.putString("Task_" + i, stockList.get(i).getString());
			}
			editor.commit();
			// end save data for internal storage

			// the duration that recall this function
			handler.postDelayed(this, 10000);
		}
	};
}
